package com.qqim.client.ui;

import com.qqim.client.ClientMain;
import com.qqim.client.cache.CacheManager;
import com.qqim.client.network.NetworkManager;
import com.qqim.common.entity.Message;
import com.qqim.common.entity.User;
import com.qqim.common.protocol.Protocol;
import com.qqim.common.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;

/**
 * 现代化主窗口 - 参考QQ/微信设计
 */
public class MainWindow extends JFrame implements NetworkManager.MessageListener, CacheManager.CacheListener {
    private static final Logger logger = LoggerFactory.getLogger(MainWindow.class);
    
    // 颜色主题
    private static final Color BACKGROUND_COLOR = new Color(248, 249, 251);
    private static final Color SIDEBAR_COLOR = new Color(237, 239, 242);
    private static final Color CHAT_HEADER_COLOR = new Color(255, 255, 255);
    private static final Color MY_MESSAGE_COLOR = new Color(162, 218, 255);
    private static final Color OTHER_MESSAGE_COLOR = new Color(255, 255, 255);
    private static final Color BORDER_COLOR = new Color(230, 230, 230);
    private static final Color TEXT_COLOR = new Color(51, 51, 51);
    private static final Color TIME_COLOR = new Color(153, 153, 153);
    
    private final ClientMain clientMain;
    
    // UI组件
    private DefaultListModel<User> userListModel;
    private JList<User> userList;
    private JPanel chatPanel;
    private JScrollPane chatScrollPane;
    private JTextField messageField;
    private JButton sendButton;
    private JButton imageButton;
    private JButton emojiButton;
    private JLabel currentChatLabel;
    private JLabel currentUserStatusLabel;
    
    private User currentChatUser;
    
    public MainWindow(ClientMain clientMain) {
        this.clientMain = clientMain;
        
        // 在初始化前进行字符编码验证
        validateCharacterEncoding();
        
        initComponents();
        layoutComponents();
        bindEvents();
        applyModernTheme();
        
        setTitle("QQ即时通信");
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setSize(900, 650);
        setLocationRelativeTo(null);
        setMinimumSize(new Dimension(800, 500));
        
        // 设置消息监听器
        clientMain.getNetworkManager().setMessageListener(this);
        clientMain.getCacheManager().addCacheListener(this);
    }
    
    /**
     * 验证字符编码设置
     */
    private void validateCharacterEncoding() {
        System.out.println("=== MainWindow 字符编码验证 ===");
        
        // 测试字符串
        String testString = "中文测试😊👍";
        
        try {
            // 检查默认字符集
            java.nio.charset.Charset defaultCharset = java.nio.charset.Charset.defaultCharset();
            System.out.println("默认字符集: " + defaultCharset.name());
            
            // 测试字符编码转换
            byte[] utf8Bytes = testString.getBytes("UTF-8");
            String decodedString = new String(utf8Bytes, "UTF-8");
            
            System.out.println("原始字符串: " + testString);
            System.out.println("UTF-8编码后解码: " + decodedString);
            System.out.println("编码是否一致: " + testString.equals(decodedString));
            
            // 检查系统属性
            System.out.println("file.encoding: " + System.getProperty("file.encoding"));
            System.out.println("sun.jnu.encoding: " + System.getProperty("sun.jnu.encoding"));
            System.out.println("user.language: " + System.getProperty("user.language"));
            System.out.println("user.country: " + System.getProperty("user.country"));
            
        } catch (Exception e) {
            System.err.println("字符编码验证失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        System.out.println("=============================");
    }
    
    private void initComponents() {
        // 用户列表
        userListModel = new DefaultListModel<>();
        userList = new JList<>(userListModel);
        userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        userList.setCellRenderer(new ModernUserListCellRenderer());
        userList.setFixedCellHeight(60);
        
        // 聊天面板
        chatPanel = new JPanel();
        chatPanel.setLayout(new BoxLayout(chatPanel, BoxLayout.Y_AXIS));
        chatPanel.setBackground(BACKGROUND_COLOR);
        chatScrollPane = new JScrollPane(chatPanel);
        chatScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        chatScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        chatScrollPane.setBorder(null);
        
        // 消息输入
        messageField = new JTextField();
        
        // 为输入框应用混合字体（支持中文和emoji）
        Font mixedFont = getOptimalMixedFont(14);
        messageField.setFont(mixedFont);
        
        // 强化输入框的文本渲染
        messageField.putClientProperty("awt.useSystemAAFontSettings", "on");
        messageField.putClientProperty("swing.aatext", true);
        messageField.setComponentOrientation(java.awt.ComponentOrientation.LEFT_TO_RIGHT);
        
        messageField.setBorder(new EmptyBorder(10, 15, 10, 15));
        
        // 按钮
        sendButton = new JButton("发送");
        imageButton = new JButton("📷");
        emojiButton = new JButton("😊");
        
        // 聊天标题
        currentChatLabel = new JLabel("请选择一个用户开始聊天");
        currentChatLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        currentChatLabel.setForeground(TEXT_COLOR);
        
        currentUserStatusLabel = new JLabel("在线");
        currentUserStatusLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        currentUserStatusLabel.setForeground(TIME_COLOR);
    }
    
    private void layoutComponents() {
        setLayout(new BorderLayout());
        
        // 左侧面板 - 用户列表
        JPanel leftPanel = createLeftPanel();
        
        // 右侧面板 - 聊天区域
        JPanel rightPanel = createRightPanel();
        
        add(leftPanel, BorderLayout.WEST);
        add(rightPanel, BorderLayout.CENTER);
    }
    
    private JPanel createLeftPanel() {
        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setBackground(SIDEBAR_COLOR);
        leftPanel.setPreferredSize(new Dimension(280, 0));
        leftPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, BORDER_COLOR));
        
        // 标题
        JLabel titleLabel = new JLabel("联系人");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(TEXT_COLOR);
        titleLabel.setBorder(new EmptyBorder(20, 20, 15, 20));
        
        // 用户列表
        userList.setBackground(SIDEBAR_COLOR);
        JScrollPane userScrollPane = new JScrollPane(userList);
        userScrollPane.setBorder(null);
        userScrollPane.setBackground(SIDEBAR_COLOR);
        
        leftPanel.add(titleLabel, BorderLayout.NORTH);
        leftPanel.add(userScrollPane, BorderLayout.CENTER);
        
        return leftPanel;
    }
    
    private JPanel createRightPanel() {
        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.setBackground(BACKGROUND_COLOR);
        
        // 聊天头部
        JPanel headerPanel = createChatHeader();
        
        // 聊天内容区域
        chatScrollPane.getViewport().setBackground(BACKGROUND_COLOR);
        
        // 输入区域
        JPanel inputPanel = createInputPanel();
        
        rightPanel.add(headerPanel, BorderLayout.NORTH);
        rightPanel.add(chatScrollPane, BorderLayout.CENTER);
        rightPanel.add(inputPanel, BorderLayout.SOUTH);
        
        return rightPanel;
    }
    
    private JPanel createChatHeader() {
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setBackground(CHAT_HEADER_COLOR);
        headerPanel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createMatteBorder(0, 0, 1, 0, BORDER_COLOR),
            new EmptyBorder(15, 20, 15, 20)
        ));
        
        JPanel titlePanel = new JPanel();
        titlePanel.setLayout(new BoxLayout(titlePanel, BoxLayout.Y_AXIS));
        titlePanel.setBackground(CHAT_HEADER_COLOR);
        
        titlePanel.add(currentChatLabel);
        titlePanel.add(Box.createVerticalStrut(3));
        titlePanel.add(currentUserStatusLabel);
        
        headerPanel.add(titlePanel, BorderLayout.WEST);
        
        return headerPanel;
    }
    
    private JPanel createInputPanel() {
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.setBackground(CHAT_HEADER_COLOR);
        inputPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, BORDER_COLOR));
        
        // 工具栏
        JPanel toolPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        toolPanel.setBackground(CHAT_HEADER_COLOR);
        toolPanel.setBorder(new EmptyBorder(10, 15, 5, 15));
        
        styleButton(emojiButton);
        styleButton(imageButton);
        
        toolPanel.add(emojiButton);
        toolPanel.add(Box.createHorizontalStrut(10));
        toolPanel.add(imageButton);
        
        // 消息输入区域
        JPanel messagePanel = new JPanel(new BorderLayout());
        messagePanel.setBackground(CHAT_HEADER_COLOR);
        messagePanel.setBorder(new EmptyBorder(5, 15, 15, 15));
        
        messageField.setPreferredSize(new Dimension(0, 40));
        messageField.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(BORDER_COLOR, 1),
            new EmptyBorder(8, 12, 8, 12)
        ));
        
        sendButton.setPreferredSize(new Dimension(80, 40));
        sendButton.setBackground(new Color(64, 158, 255));
        sendButton.setForeground(Color.WHITE);
        sendButton.setBorder(null);
        sendButton.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        sendButton.setFocusPainted(false);
        sendButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        // 创建输入和按钮的容器
        JPanel inputContainer = new JPanel(new BorderLayout());
        inputContainer.setBackground(CHAT_HEADER_COLOR);
        inputContainer.add(messageField, BorderLayout.CENTER);
        inputContainer.add(Box.createHorizontalStrut(10), BorderLayout.LINE_END);
        
        // 按钮容器
        JPanel buttonContainer = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        buttonContainer.setBackground(CHAT_HEADER_COLOR);
        buttonContainer.add(sendButton);
        
        messagePanel.add(inputContainer, BorderLayout.CENTER);
        messagePanel.add(buttonContainer, BorderLayout.EAST);
        
        inputPanel.add(toolPanel, BorderLayout.NORTH);
        inputPanel.add(messagePanel, BorderLayout.CENTER);
        
        return inputPanel;
    }
    
    private void styleButton(JButton button) {
        button.setBackground(CHAT_HEADER_COLOR);
        button.setBorder(new EmptyBorder(8, 12, 8, 12));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        // 获取按钮文本以判断是否为emoji按钮
        String buttonText = button.getText();
        
        if (buttonText != null && !buttonText.trim().isEmpty()) {
            // 检查是否包含emoji字符
            boolean containsEmoji = false;
            for (char c : buttonText.toCharArray()) {
                if (isEmojiCharacter(c)) {
                    containsEmoji = true;
                    break;
                }
            }
            
            if (containsEmoji) {
                // 为emoji按钮设置特殊字体
                System.out.println("检测到emoji按钮: " + buttonText);
                setOptimalEmojiFont(button, buttonText, 16);
            } else {
                // 为普通按钮设置中文字体
                Font chineseFont = getOptimalChineseFont();
                Font buttonFont = new Font(chineseFont.getName(), Font.PLAIN, 16);
                button.setFont(buttonFont);
            }
        } else {
            // 默认字体
            button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 16));
        }
    }
    
    /**
     * 检查字符是否为emoji字符
     */
    private boolean isEmojiCharacter(char c) {
        // 检查常见的emoji Unicode范围
        return (c >= 0x1F600 && c <= 0x1F64F) ||  // 表情符号
               (c >= 0x1F300 && c <= 0x1F5FF) ||  // 杂项符号和象形文字
               (c >= 0x1F680 && c <= 0x1F6FF) ||  // 交通和地图符号
               (c >= 0x1F1E0 && c <= 0x1F1FF) ||  // 区域指示符号
               (c >= 0x2600 && c <= 0x26FF) ||    // 杂项符号
               (c >= 0x2700 && c <= 0x27BF) ||    // 印刷符号
               (c >= 0xFE00 && c <= 0xFE0F) ||    // 变异选择器
               (c >= 0x1F900 && c <= 0x1F9FF) ||  // 补充符号和象形文字
               (c >= 0x1F018 && c <= 0x1F270) ||  // 封闭式字母数字补充
               (c == 0x200D);                     // 零宽连接符
    }
    
    private void applyModernTheme() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            // 忽略异常
        }
    }
    
    private void bindEvents() {
        // 窗口关闭事件
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                int option = JOptionPane.showConfirmDialog(
                    MainWindow.this,
                    "确定要退出吗？",
                    "确认退出",
                    JOptionPane.YES_NO_OPTION
                );
                
                if (option == JOptionPane.YES_OPTION) {
                    User currentUser = clientMain.getCacheManager().getCurrentUser();
                    if (currentUser != null) {
                        clientMain.getNetworkManager().logout(currentUser.getUserId());
                    }
                    System.exit(0);
                }
            }
        });
        
        // 用户列表选择事件
        userList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                User selectedUser = userList.getSelectedValue();
                if (selectedUser != null) {
                    startChatWith(selectedUser);
                }
            }
        });
        
        // 发送按钮
        sendButton.addActionListener(e -> sendMessage());
        
        // 图片按钮
        imageButton.addActionListener(e -> sendImage());
        
        // 表情按钮
        emojiButton.addActionListener(e -> showEmojiPanel());
        
        // 回车发送
        messageField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    sendMessage();
                }
            }
        });
        
        // 鼠标悬停效果
        addHoverEffect(sendButton);
        addHoverEffect(imageButton);
        addHoverEffect(emojiButton);
    }
    
    private void addHoverEffect(JButton button) {
        Color originalColor = button.getBackground();
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                if (button == sendButton) {
                    button.setBackground(new Color(45, 140, 240));
                } else {
                    button.setBackground(new Color(245, 245, 245));
                }
            }
            
            @Override
            public void mouseExited(MouseEvent e) {
                button.setBackground(originalColor);
            }
        });
    }
    
    private void startChatWith(User user) {
        this.currentChatUser = user;
        currentChatLabel.setText(user.getNickname());
        currentUserStatusLabel.setText("在线");
        
        // 清空聊天面板并加载历史记录
        chatPanel.removeAll();
        loadChatHistory();
        chatPanel.revalidate();
        chatPanel.repaint();
        
        // 确保输入框可用
        messageField.setEnabled(true);
        sendButton.setEnabled(true);
        imageButton.setEnabled(true);
        emojiButton.setEnabled(true);
    }
    
    private void loadChatHistory() {
        if (currentChatUser != null) {
            User currentUser = clientMain.getCacheManager().getCurrentUser();
            if (currentUser != null) {
                // 从缓存中加载历史消息
                java.util.List<Message> chatMessages = clientMain.getCacheManager().getChatMessages(
                    currentUser.getUserId(), 
                    currentChatUser.getUserId()
                );
                
                if (chatMessages != null && !chatMessages.isEmpty()) {
                    // 显示历史消息
                    for (Message message : chatMessages) {
                        String senderId = message.getSenderId();
                        String content = message.getContent();
                        
                        if (senderId.equals(currentUser.getUserId())) {
                            // 我发送的消息
                            if ("text".equals(message.getMessageType()) && message.getContent() != null) {
                                addMyMessage(content);
                            } else if ("image".equals(message.getMessageType()) && message.getFilePath() != null) {
                                // 处理图片消息
                                try {
                                    byte[] imageData = FileUtils.readFile(message.getFilePath());
                                    if (imageData != null) {
                                        addMyImageMessage(imageData);
                                    }
                                } catch (Exception e) {
                                    logger.error("加载历史图片消息失败", e);
                                }
                            }
                        } else {
                            // 对方发送的消息
                            String senderName = currentChatUser.getNickname();
                            if ("text".equals(message.getMessageType()) && message.getContent() != null) {
                                addOtherMessage(senderName, content);
                            } else if ("image".equals(message.getMessageType()) && message.getFilePath() != null) {
                                // 处理图片消息
                                try {
                                    byte[] imageData = FileUtils.readFile(message.getFilePath());
                                    if (imageData != null) {
                                        addOtherImageMessage(senderName, imageData);
                                    }
                                } catch (Exception e) {
                                    logger.error("加载历史图片消息失败", e);
                                }
                            }
                        }
                    }
                } else {
                    // 没有历史消息，显示欢迎消息
                    addWelcomeMessage();
                }
            }
        }
    }
    
    private void addWelcomeMessage() {
        if (currentChatUser != null) {
            JPanel welcomePanel = createSystemMessage("开始与 " + currentChatUser.getNickname() + " 的聊天");
            chatPanel.add(welcomePanel);
            chatPanel.add(Box.createVerticalStrut(10));
        }
    }
    
    private void sendMessage() {
        if (currentChatUser == null) {
            JOptionPane.showMessageDialog(this, "请先选择聊天对象", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String content = messageField.getText().trim();
        if (content.isEmpty()) {
            return;
        }
        
        User currentUser = clientMain.getCacheManager().getCurrentUser();
        
        // 发送消息
        boolean success = clientMain.getNetworkManager().sendTextMessage(
            currentUser.getUserId(),
            currentChatUser.getUserId(),
            content
        );
        
        if (success) {
            // 显示在聊天区域
            addMyMessage(content);
            messageField.setText("");
            
            // 保存到缓存
            Message message = Message.createTextMessage(
                currentUser.getUserId(),
                currentChatUser.getUserId(),
                content
            );
            clientMain.getCacheManager().addChatMessage(message);
        }
    }
    
    private void sendImage() {
        System.out.println("=== 发送图片开始 ===");
        
        if (currentChatUser == null) {
            System.out.println("当前聊天用户为空");
            JOptionPane.showMessageDialog(this, "请先选择聊天对象", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        System.out.println("当前聊天用户: " + currentChatUser.getNickname());
        
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new FileNameExtensionFilter("图片文件", "jpg", "jpeg", "png", "gif", "bmp"));
        
        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            System.out.println("选择的文件: " + selectedFile.getAbsolutePath());
            System.out.println("文件大小: " + selectedFile.length() + " 字节");
            
            try {
                // 读取图片文件
                byte[] imageData = FileUtils.readFile(selectedFile.getAbsolutePath());
                if (imageData != null) {
                    System.out.println("图片文件读取成功: " + imageData.length + " 字节");
                    
                    String base64Data = Base64.getEncoder().encodeToString(imageData);
                    System.out.println("Base64编码完成: " + base64Data.length() + " 字符");
                    
                    User currentUser = clientMain.getCacheManager().getCurrentUser();
                    System.out.println("当前用户: " + currentUser.getUserId());
                    
                    // 发送图片
                    boolean success = clientMain.getNetworkManager().sendImage(
                        currentUser.getUserId(),
                        currentChatUser.getUserId(),
                        base64Data
                    );
                    
                    System.out.println("网络发送结果: " + success);
                    
                    if (success) {
                        // 显示图片在聊天区域
                        System.out.println("开始显示我的图片消息");
                        addMyImageMessage(imageData);
                        
                        // 保存到本地
                        String imagePath = clientMain.getCacheManager().saveImageToCache(base64Data, selectedFile.getName());
                        System.out.println("图片保存路径: " + imagePath);
                        
                        Message message = Message.createImageMessage(
                            currentUser.getUserId(),
                            currentChatUser.getUserId(),
                            imagePath,
                            imageData.length
                        );
                        clientMain.getCacheManager().addChatMessage(message);
                        
                        System.out.println("图片发送流程完成");
                    } else {
                        System.err.println("网络发送失败");
                        JOptionPane.showMessageDialog(this, "图片发送失败", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    System.err.println("图片文件读取失败");
                    JOptionPane.showMessageDialog(this, "无法读取图片文件", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                System.err.println("发送图片异常: " + e.getMessage());
                e.printStackTrace();
                logger.error("发送图片失败", e);
                JOptionPane.showMessageDialog(this, "发送图片失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            System.out.println("用户取消选择文件");
        }
        System.out.println("================");
    }
    
    private void showEmojiPanel() {
        System.out.println("=== 显示表情面板 ===");
        
        // 简单的表情面板
        String[] emojis = {"😀", "😂", "😍", "😢", "😎", "👍", "❤️", "🎉"};
        JPopupMenu emojiMenu = new JPopupMenu();
        
        JPanel emojiPanel = new JPanel(new GridLayout(2, 4, 5, 5));
        emojiPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
        emojiPanel.setBackground(Color.WHITE);
        
        for (String emoji : emojis) {
            System.out.println("创建emoji按钮: " + emoji);
            
            JButton emojiBtn = new JButton(emoji);
            
            // 使用优化后的emoji字体选择
            setOptimalEmojiFont(emojiBtn, emoji, 20);
            
            // 设置按钮样式
            emojiBtn.setBorder(new EmptyBorder(8, 8, 8, 8));
            emojiBtn.setBackground(Color.WHITE);
            emojiBtn.setFocusPainted(false);
            emojiBtn.setCursor(new Cursor(Cursor.HAND_CURSOR));
            
            // 添加悬停效果
            emojiBtn.addMouseListener(new java.awt.event.MouseAdapter() {
                @Override
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    emojiBtn.setBackground(new Color(245, 245, 245));
                }
                
                @Override
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    emojiBtn.setBackground(Color.WHITE);
                }
            });
            
            // 点击事件
            emojiBtn.addActionListener(e -> {
                String currentText = messageField.getText();
                messageField.setText(currentText + emoji);
                emojiMenu.setVisible(false);
                
                // 将焦点回到输入框
                messageField.requestFocus();
                
                System.out.println("插入emoji: " + emoji);
            });
            
            emojiPanel.add(emojiBtn);
        }
        
        emojiMenu.add(emojiPanel);
        emojiMenu.show(emojiButton, 0, -emojiMenu.getPreferredSize().height);
        
        System.out.println("表情面板显示完成");
    }
    
    private void addMyMessage(String content) {
        JPanel messagePanel = createMessageBubble(content, true, false);
        chatPanel.add(messagePanel);
        chatPanel.add(Box.createVerticalStrut(5));
        chatPanel.revalidate();
        chatPanel.repaint();
        scrollToBottom();
    }
    
    private void addOtherMessage(String sender, String content) {
        addSenderLabel(sender);
        JPanel messagePanel = createMessageBubble(content, false, false);
        chatPanel.add(messagePanel);
        chatPanel.add(Box.createVerticalStrut(5));
        chatPanel.revalidate();
        chatPanel.repaint();
        scrollToBottom();
    }
    
    private void addMyImageMessage(byte[] imageData) {
        System.out.println("=== 添加我的图片消息 ===");
        System.out.println("图片数据大小: " + (imageData != null ? imageData.length : 0) + " 字节");
        
        JPanel messagePanel = createImageBubble(imageData, true);
        if (messagePanel != null) {
            chatPanel.add(messagePanel);
            chatPanel.add(Box.createVerticalStrut(5));
            chatPanel.revalidate();
            chatPanel.repaint();
            scrollToBottom();
            System.out.println("图片消息添加成功");
        } else {
            System.err.println("图片消息面板创建失败");
        }
        System.out.println("====================");
    }

    private void addOtherImageMessage(String sender, byte[] imageData) {
        System.out.println("=== 添加对方图片消息 ===");
        System.out.println("发送者: " + sender);
        System.out.println("图片数据大小: " + (imageData != null ? imageData.length : 0) + " 字节");
        
        addSenderLabel(sender);
        JPanel messagePanel = createImageBubble(imageData, false);
        if (messagePanel != null) {
            chatPanel.add(messagePanel);
            chatPanel.add(Box.createVerticalStrut(5));
            chatPanel.revalidate();
            chatPanel.repaint();
            scrollToBottom();
            System.out.println("对方图片消息添加成功");
        } else {
            System.err.println("对方图片消息面板创建失败");
        }
        System.out.println("====================");
    }
    
    private void addSenderLabel(String sender) {
        JLabel senderLabel = new JLabel(sender);
        senderLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        senderLabel.setForeground(TIME_COLOR);
        senderLabel.setBorder(new EmptyBorder(0, 15, 5, 0));
        chatPanel.add(senderLabel);
    }
    
    private JPanel createMessageBubble(String content, boolean isMe, boolean isImage) {
        JPanel bubblePanel = new JPanel();
        bubblePanel.setLayout(new BoxLayout(bubblePanel, BoxLayout.X_AXIS));
        bubblePanel.setBackground(BACKGROUND_COLOR);
        
        // 确保内容不为空
        if (content == null || content.trim().isEmpty()) {
            content = "[空消息]";
        }
        
        // 使用JTextArea更好地支持文本显示和换行
        JTextArea messageArea = new JTextArea(content);
        
        // === 强化字体设置 ===
        // 获取最佳中文字体
        Font optimalFont = getOptimalChineseFont();
        messageArea.setFont(optimalFont);
        
        // === 强化文本渲染设置 ===
        messageArea.setComponentOrientation(java.awt.ComponentOrientation.LEFT_TO_RIGHT);
        
        // 启用抗锯齿渲染
        messageArea.putClientProperty("awt.useSystemAAFontSettings", "on");
        messageArea.putClientProperty("swing.aatext", true);
        
        // 设置字符编码相关属性
        messageArea.putClientProperty("JComponent.sizeVariant", "regular");
        
        // 调试：输出消息内容的字节信息
        debugMessageContent(content);
        
        messageArea.setEditable(false);
        messageArea.setLineWrap(true);
        messageArea.setWrapStyleWord(true);
        messageArea.setOpaque(true);
        
        // 设置文本颜色 - 确保对比度
        Color textColor = isMe ? Color.WHITE : Color.BLACK;
        Color backgroundColor = isMe ? MY_MESSAGE_COLOR : OTHER_MESSAGE_COLOR;
        
        messageArea.setForeground(textColor);
        messageArea.setBackground(backgroundColor);
        
        // 设置内边距
        messageArea.setBorder(new EmptyBorder(10, 15, 10, 15));
        
        // 设置最大宽度
        messageArea.setColumns(20);
        messageArea.setRows(0); // 自动调整行数
        
        // 创建带圆角的容器面板
        JPanel messageBubble = new JPanel(new BorderLayout());
        messageBubble.setBackground(backgroundColor);
        messageBubble.setBorder(new RoundedBorder(15, backgroundColor));
        messageBubble.add(messageArea, BorderLayout.CENTER);
        
        // 设置最大宽度
        messageBubble.setMaximumSize(new Dimension(250, Integer.MAX_VALUE));
        
        // 添加时间戳
        JLabel timeLabel = new JLabel(getCurrentTime());
        timeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 10));
        timeLabel.setForeground(TIME_COLOR);
        
        if (isMe) {
            bubblePanel.add(Box.createHorizontalGlue());
            bubblePanel.add(timeLabel);
            bubblePanel.add(Box.createHorizontalStrut(5));
            bubblePanel.add(messageBubble);
            bubblePanel.add(Box.createHorizontalStrut(15));
        } else {
            bubblePanel.add(Box.createHorizontalStrut(15));
            bubblePanel.add(messageBubble);
            bubblePanel.add(Box.createHorizontalStrut(5));
            bubblePanel.add(timeLabel);
            bubblePanel.add(Box.createHorizontalGlue());
        }
        
        return bubblePanel;
    }
    
    private JPanel createImageBubble(byte[] imageData, boolean isMe) {
        System.out.println("=== 创建图片气泡 ===");
        System.out.println("图片数据: " + (imageData != null ? imageData.length + " 字节" : "null"));
        System.out.println("是否为我的消息: " + isMe);
        
        JPanel bubblePanel = new JPanel();
        bubblePanel.setLayout(new BoxLayout(bubblePanel, BoxLayout.X_AXIS));
        bubblePanel.setBackground(BACKGROUND_COLOR);
        
        if (imageData == null || imageData.length == 0) {
            System.err.println("图片数据为空");
            return createMessageBubble("[图片数据为空]", isMe, false);
        }
        
        try {
            // 调试：输出图片数据的前几个字节
            System.out.print("图片数据前10字节: ");
            for (int i = 0; i < Math.min(10, imageData.length); i++) {
                System.out.print(String.format("%02X ", imageData[i]));
            }
            System.out.println();
            
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData));
            if (image == null) {
                System.err.println("ImageIO.read返回null，可能图片格式不支持");
                return createMessageBubble("[不支持的图片格式]", isMe, false);
            }
            
            System.out.println("图片读取成功: " + image.getWidth() + "x" + image.getHeight());
            
            // 缩放图片
            int maxWidth = 200;
            int maxHeight = 200;
            Image scaledImage = scaleImage(image, maxWidth, maxHeight);
            System.out.println("图片缩放完成");
            
            // 创建图片容器面板
            JPanel imageContainer = new JPanel(new BorderLayout());
            imageContainer.setBackground(Color.WHITE);
            imageContainer.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                new EmptyBorder(5, 5, 5, 5)
            ));
            
            JLabel imageLabel = new JLabel(new ImageIcon(scaledImage));
            imageLabel.setHorizontalAlignment(SwingConstants.CENTER);
            imageLabel.setVerticalAlignment(SwingConstants.CENTER);
            imageContainer.add(imageLabel, BorderLayout.CENTER);
            
            // 设置容器大小
            Dimension imageSize = new Dimension(scaledImage.getWidth(null) + 12, scaledImage.getHeight(null) + 12);
            imageContainer.setPreferredSize(imageSize);
            imageContainer.setMaximumSize(imageSize);
            imageContainer.setMinimumSize(imageSize);
            
            // 添加时间戳
            JLabel timeLabel = new JLabel(getCurrentTime());
            timeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 10));
            timeLabel.setForeground(TIME_COLOR);
            
            if (isMe) {
                bubblePanel.add(Box.createHorizontalGlue());
                bubblePanel.add(timeLabel);
                bubblePanel.add(Box.createHorizontalStrut(5));
                bubblePanel.add(imageContainer);
                bubblePanel.add(Box.createHorizontalStrut(15));
            } else {
                bubblePanel.add(Box.createHorizontalStrut(15));
                bubblePanel.add(imageContainer);
                bubblePanel.add(Box.createHorizontalStrut(5));
                bubblePanel.add(timeLabel);
                bubblePanel.add(Box.createHorizontalGlue());
            }
            
            System.out.println("图片气泡创建成功");
            
        } catch (Exception e) {
            System.err.println("创建图片气泡失败: " + e.getMessage());
            e.printStackTrace();
            logger.error("显示图片失败", e);
            // 显示错误消息
            return createMessageBubble("[图片加载失败: " + e.getMessage() + "]", isMe, false);
        }
        
        System.out.println("=================");
        return bubblePanel;
    }
    
    private Image scaleImage(BufferedImage original, int maxWidth, int maxHeight) {
        int width = original.getWidth();
        int height = original.getHeight();
        
        double scaleX = (double) maxWidth / width;
        double scaleY = (double) maxHeight / height;
        double scale = Math.min(scaleX, scaleY);
        
        if (scale >= 1.0) {
            return original;
        }
        
        int newWidth = (int) (width * scale);
        int newHeight = (int) (height * scale);
        
        return original.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
    }
    
    private JPanel createSystemMessage(String content) {
        JPanel systemPanel = new JPanel();
        systemPanel.setLayout(new BoxLayout(systemPanel, BoxLayout.X_AXIS));
        systemPanel.setBackground(BACKGROUND_COLOR);
        
        JLabel systemLabel = new JLabel(content);
        systemLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        systemLabel.setForeground(TIME_COLOR);
        systemLabel.setHorizontalAlignment(SwingConstants.CENTER);
        
        systemPanel.add(Box.createHorizontalGlue());
        systemPanel.add(systemLabel);
        systemPanel.add(Box.createHorizontalGlue());
        
        return systemPanel;
    }
    
    private String getCurrentTime() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm"));
    }
    
    /**
     * 获取最佳中文字体
     */
    private Font getOptimalChineseFont() {
        // 中文字体优先级列表
        String[] chineseFonts = {
            "Microsoft YaHei UI",     // Windows 10/11 推荐
            "Microsoft YaHei",        // Windows 经典
            "Segoe UI",              // Windows 系统字体
            "PingFang SC",           // macOS 简体中文
            "Hiragino Sans GB",      // macOS 备选
            "Source Han Sans CN",    // Adobe 思源黑体
            "Noto Sans CJK SC",      // Google Noto 字体
            "SimSun",                // 宋体
            "SimHei",                // 黑体
            "NSimSun",               // 新宋体
            Font.SANS_SERIF,         // 系统默认无衬线字体
            Font.DIALOG              // 系统对话框字体
        };
        
        // 测试字符：包含常用中文字符、数字、emoji
        String testChars = "中文测试abc123😊👍";
        
        for (String fontName : chineseFonts) {
            try {
                Font font = new Font(fontName, Font.PLAIN, 14);
                
                // 检查字体是否能显示所有测试字符
                boolean canDisplayAll = true;
                for (char c : testChars.toCharArray()) {
                    if (!font.canDisplay(c)) {
                        canDisplayAll = false;
                        break;
                    }
                }
                
                if (canDisplayAll) {
                    System.out.println("选择字体: " + fontName + " (支持所有测试字符)");
                    return font;
                }
            } catch (Exception e) {
                // 忽略字体创建失败的情况
            }
        }
        
        // 如果都不支持，使用系统默认字体
        Font fallbackFont = new Font(Font.SANS_SERIF, Font.PLAIN, 14);
        System.out.println("使用回退字体: " + fallbackFont.getName());
        return fallbackFont;
    }
    
    /**
     * 获取最佳Emoji字体
     */
    private Font getOptimalEmojiFont(int fontSize, String testEmoji) {
        System.out.println("=== 选择Emoji字体 ===");
        System.out.println("测试字符: " + testEmoji);
        System.out.println("字体大小: " + fontSize);
        
        // Emoji字体优先级列表
        String[] emojiFonts = {
            "Segoe UI Emoji",         // Windows 推荐emoji字体
            "Apple Color Emoji",      // macOS emoji字体
            "Noto Color Emoji",       // Google emoji字体
            "Noto Emoji",             // Google 单色emoji字体
            "Twemoji Mozilla",        // Mozilla emoji字体
            "Microsoft YaHei UI",     // Windows 10/11 支持部分emoji
            "Microsoft YaHei",        // Windows 经典字体
            "Segoe UI",              // Windows 系统字体
            "Arial Unicode MS",       // 跨平台Unicode字体
            "DejaVu Sans",           // Linux常用字体
            Font.SANS_SERIF,         // 系统默认无衬线字体
            Font.DIALOG              // 系统对话框字体
        };
        
        for (String fontName : emojiFonts) {
            try {
                Font font = new Font(fontName, Font.PLAIN, fontSize);
                
                // 测试是否能显示emoji字符
                boolean canDisplayEmoji = true;
                if (testEmoji != null && !testEmoji.isEmpty()) {
                    for (char c : testEmoji.toCharArray()) {
                        if (!font.canDisplay(c)) {
                            canDisplayEmoji = false;
                            break;
                        }
                    }
                }
                
                if (canDisplayEmoji) {
                    System.out.println("选择Emoji字体: " + fontName + " (支持测试字符)");
                    return font;
                }
            } catch (Exception e) {
                // 忽略字体创建失败的情况
            }
        }
        
        // 如果都不支持，使用系统默认字体
        Font fallbackFont = new Font(Font.SANS_SERIF, Font.PLAIN, fontSize);
        System.out.println("使用Emoji回退字体: " + fallbackFont.getName());
        return fallbackFont;
    }
    
    /**
     * 为指定按钮设置最佳Emoji字体
     */
    private void setOptimalEmojiFont(JButton button, String buttonText, int fontSize) {
        Font emojiFont = getOptimalEmojiFont(fontSize, buttonText);
        button.setFont(emojiFont);
        
        // 设置渲染属性
        button.putClientProperty("awt.useSystemAAFontSettings", "on");
        button.putClientProperty("swing.aatext", true);
        
        System.out.println("为按钮 '" + buttonText + "' 设置字体: " + emojiFont.getName());
    }
    
    /**
     * 获取最佳混合字体（同时支持中文和emoji）
     */
    private Font getOptimalMixedFont(int fontSize) {
        System.out.println("=== 选择混合字体 ===");
        System.out.println("字体大小: " + fontSize);
        
        // 测试字符：中文 + emoji 
        String testString = "中文测试😊👍";
        
        // 混合字体优先级列表（既支持中文又支持emoji）
        String[] mixedFonts = {
            "Segoe UI Emoji",         // Windows emoji字体，部分支持中文
            "Microsoft YaHei UI",     // Windows 10/11 推荐，支持部分emoji
            "Microsoft YaHei",        // Windows 经典，支持部分emoji
            "Segoe UI",              // Windows 系统字体
            "Apple Color Emoji",      // macOS emoji字体
            "Noto Color Emoji",       // Google emoji字体
            "PingFang SC",           // macOS 简体中文
            "Hiragino Sans GB",      // macOS 备选
            "Source Han Sans CN",    // Adobe 思源黑体
            "Noto Sans CJK SC",      // Google Noto 字体
            "SimSun",                // 宋体
            "SimHei",                // 黑体
            Font.SANS_SERIF,         // 系统默认无衬线字体
            Font.DIALOG              // 系统对话框字体
        };
        
        for (String fontName : mixedFonts) {
            try {
                Font font = new Font(fontName, Font.PLAIN, fontSize);
                
                // 统计支持的字符数
                int supportedCount = 0;
                for (char c : testString.toCharArray()) {
                    if (font.canDisplay(c)) {
                        supportedCount++;
                    }
                }
                
                // 如果支持大部分字符（至少80%），则选择此字体
                double supportRate = (double) supportedCount / testString.length();
                if (supportRate >= 0.8) {
                    System.out.println("选择混合字体: " + fontName + " (支持率: " + String.format("%.1f%%", supportRate * 100) + ")");
                    return font;
                }
            } catch (Exception e) {
                // 忽略字体创建失败的情况
            }
        }
        
        // 如果都不理想，使用系统默认字体
        Font fallbackFont = new Font(Font.SANS_SERIF, Font.PLAIN, fontSize);
        System.out.println("使用混合回退字体: " + fallbackFont.getName());
        return fallbackFont;
    }
    
    /**
     * 调试消息内容的字符编码
     */
    private void debugMessageContent(String content) {
        if (content != null && !content.isEmpty()) {
            try {
                // 输出字符串的字节表示
                byte[] utf8Bytes = content.getBytes("UTF-8");
                byte[] gbkBytes = content.getBytes("GBK");
                
                System.out.println("=== 消息内容调试 ===");
                System.out.println("原始内容: " + content);
                System.out.println("内容长度: " + content.length() + " 字符");
                System.out.println("UTF-8字节数: " + utf8Bytes.length);
                System.out.println("GBK字节数: " + gbkBytes.length);
                
                // 输出每个字符的Unicode码点
                System.out.print("Unicode码点: ");
                for (int i = 0; i < content.length(); i++) {
                    char c = content.charAt(i);
                    System.out.print("U+" + Integer.toHexString(c).toUpperCase() + " ");
                }
                System.out.println();
                System.out.println("==================");
                
            } catch (Exception e) {
                System.err.println("调试消息内容失败: " + e.getMessage());
            }
        }
    }
    
    private void scrollToBottom() {
        SwingUtilities.invokeLater(() -> {
            JScrollBar vertical = chatScrollPane.getVerticalScrollBar();
            vertical.setValue(vertical.getMaximum());
        });
    }
    
    // 实现NetworkManager.MessageListener
    @Override
    public void onMessageReceived(Protocol protocol) {
        SwingUtilities.invokeLater(() -> {
            switch (protocol.getType()) {
                case Protocol.RECEIVE_MESSAGE:
                    handleReceiveMessage(protocol);
                    break;
                case Protocol.RECEIVE_IMAGE:
                    handleReceiveImage(protocol);
                    break;
                case Protocol.USER_ONLINE:
                    handleUserOnline(protocol);
                    break;
                case Protocol.USER_OFFLINE:
                    handleUserOffline(protocol);
                    break;
                case Protocol.USER_LIST:
                    handleUserList(protocol);
                    break;
            }
        });
    }
    
    @Override
    public void onConnectionLost() {
        SwingUtilities.invokeLater(() -> {
            JOptionPane.showMessageDialog(this, "连接已断开", "网络错误", JOptionPane.ERROR_MESSAGE);
        });
    }
    
    // 实现CacheManager.CacheListener
    @Override
    public void onOnlineUsersChanged(Map<String, User> users) {
        SwingUtilities.invokeLater(() -> {
            userListModel.clear();
            User currentUser = clientMain.getCacheManager().getCurrentUser();
            
            for (User user : users.values()) {
                if (!user.getUserId().equals(currentUser.getUserId())) {
                    userListModel.addElement(user);
                }
            }
        });
    }
    
    @Override
    public void onNewMessage(Message message) {
        // 由handleReceiveMessage处理
    }
    
    private void handleReceiveMessage(Protocol protocol) {
        String senderId = protocol.getSenderId();
        String content = (String) protocol.getData();
        
        User sender = clientMain.getCacheManager().getUserById(senderId);
        String senderName = sender != null ? sender.getNickname() : senderId;
        
        // 如果是当前聊天对象的消息，显示在聊天区域
        if (currentChatUser != null && senderId.equals(currentChatUser.getUserId())) {
            addOtherMessage(senderName, content);
        }
        
        // 创建消息对象并保存
        Message message = Message.createTextMessage(senderId, protocol.getReceiverId(), content);
        clientMain.getCacheManager().addChatMessage(message);
    }
    
    private void handleReceiveImage(Protocol protocol) {
        System.out.println("=== 处理接收图片 ===");
        String senderId = protocol.getSenderId();
        String base64Data = (String) protocol.getData();
        
        System.out.println("发送者ID: " + senderId);
        System.out.println("Base64数据长度: " + (base64Data != null ? base64Data.length() : 0));
        System.out.println("当前聊天用户: " + (currentChatUser != null ? currentChatUser.getUserId() : "null"));
        
        User sender = clientMain.getCacheManager().getUserById(senderId);
        String senderName = sender != null ? sender.getNickname() : senderId;
        
        try {
            if (base64Data == null || base64Data.trim().isEmpty()) {
                System.err.println("Base64数据为空");
                return;
            }
            
            byte[] imageData = Base64.getDecoder().decode(base64Data);
            System.out.println("Base64解码成功，图片数据大小: " + imageData.length + " 字节");
            
            // 如果是当前聊天对象的消息，显示在聊天区域
            if (currentChatUser != null && senderId.equals(currentChatUser.getUserId())) {
                System.out.println("是当前聊天对象，显示图片消息");
                addOtherImageMessage(senderName, imageData);
            } else {
                System.out.println("不是当前聊天对象，不显示图片消息");
            }
            
            // 保存图片到本地
            String imagePath = clientMain.getCacheManager().saveImageToCache(base64Data, "received_image.jpg");
            System.out.println("图片保存路径: " + imagePath);
            
            Message message = Message.createImageMessage(senderId, protocol.getReceiverId(), imagePath, imageData.length);
            clientMain.getCacheManager().addChatMessage(message);
            
        } catch (Exception e) {
            System.err.println("处理接收图片失败: " + e.getMessage());
            e.printStackTrace();
            logger.error("处理接收图片失败", e);
        }
        System.out.println("==================");
    }
    
    private void handleUserOnline(Protocol protocol) {
        String userId = protocol.getSenderId();
        // 刷新用户列表
        clientMain.getNetworkManager().getUserList();
    }
    
    private void handleUserOffline(Protocol protocol) {
        String userId = protocol.getSenderId();
        clientMain.getCacheManager().removeOnlineUser(userId);
    }
    
    @SuppressWarnings("unchecked")
    private void handleUserList(Protocol protocol) {
        Map<String, Object> rawUsers = (Map<String, Object>) protocol.getData();
        Map<String, User> users = new HashMap<>();
        
        // 将LinkedTreeMap转换为User对象
        for (Map.Entry<String, Object> entry : rawUsers.entrySet()) {
            String userId = entry.getKey();
            
            if (entry.getValue() instanceof Map) {
                Map<String, Object> userMap = (Map<String, Object>) entry.getValue();
                
                User user = new User();
                user.setUserId((String) userMap.get("userId"));
                user.setNickname((String) userMap.get("nickname"));
                user.setStatus((String) userMap.get("status"));
                
                if (userMap.get("loginTime") instanceof Number) {
                    user.setLoginTime(((Number) userMap.get("loginTime")).longValue());
                }
                if (userMap.get("lastActiveTime") instanceof Number) {
                    user.setLastActiveTime(((Number) userMap.get("lastActiveTime")).longValue());
                }
                
                users.put(userId, user);
            }
        }
        
        clientMain.getCacheManager().updateOnlineUsers(users);
    }
    
    /**
     * 现代化用户列表渲染器
     */
    private class ModernUserListCellRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            
            JPanel panel = new JPanel(new BorderLayout());
            panel.setBorder(new EmptyBorder(10, 15, 10, 15));
            
            if (isSelected) {
                panel.setBackground(new Color(220, 230, 240));
            } else {
                panel.setBackground(SIDEBAR_COLOR);
            }
            
            if (value instanceof User) {
                User user = (User) value;
                
                // 头像
                JLabel avatarLabel = new JLabel("👤");
                avatarLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 24));
                avatarLabel.setPreferredSize(new Dimension(40, 40));
                avatarLabel.setHorizontalAlignment(SwingConstants.CENTER);
                
                // 用户信息
                JPanel infoPanel = new JPanel();
                infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
                infoPanel.setBackground(panel.getBackground());
                
                JLabel nameLabel = new JLabel(user.getNickname());
                nameLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
                nameLabel.setForeground(TEXT_COLOR);
                
                JLabel statusLabel = new JLabel("在线");
                statusLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
                statusLabel.setForeground(new Color(76, 175, 80));
                
                infoPanel.add(nameLabel);
                infoPanel.add(Box.createVerticalStrut(3));
                infoPanel.add(statusLabel);
                
                panel.add(avatarLabel, BorderLayout.WEST);
                panel.add(Box.createHorizontalStrut(12), BorderLayout.CENTER);
                panel.add(infoPanel, BorderLayout.CENTER);
            }
            
            return panel;
        }
    }
    
    /**
     * 圆角边框
     */
    private class RoundedBorder implements javax.swing.border.Border {
        private int radius;
        private Color color;
        
        public RoundedBorder(int radius, Color color) {
            this.radius = radius;
            this.color = color;
        }
        
        @Override
        public Insets getBorderInsets(Component c) {
            return new Insets(2, 2, 2, 2);
        }
        
        @Override
        public boolean isBorderOpaque() {
            return false;
        }
        
        @Override
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setColor(color);
            g2d.fillRoundRect(x, y, width, height, radius, radius);
            g2d.dispose();
        }
    }
} 